package info.liujiachen.security.test;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletRequest;

@SpringBootApplication
@RestController
public class ErrorPageApp {

    // 日志
    private Logger logger = LoggerFactory.getLogger(getClass());

    @RequestMapping({"/", "/home"})
    public String home() {
        return "Everyone can read the home page." +
                "<br> <a href=\"user\">user</a>" +
                "<br> <a href=\"admin\">admin</a>" +
                "<br> <a href=\"logout\">logout</a>";
    }

    @RequestMapping("/user")
    public String user() {
        return "Both user and admin can read the user page." +
                "<br> <a href=\"admin\">admin</a>" +
                "<br> <a href=\"logout\">logout</a>";
    }

    @RequestMapping("/admin")
    public String admin() {
        return "User admin can read the admin page." +
                "<br> <a href=\"user\">user</a>" +
                "<br> <a href=\"logout\">logout</a>";
    }

    @RequestMapping("/error")
    public String error(HttpServletRequest request) {
        logger.info("进入异常跳转");
        Integer statusCode = (Integer) request.getAttribute("javax.servlet.error.status_code");
        switch (statusCode) {
            case 404:
                logger.info("404异常跳转");
                return "Access page not found." +
                        "<br> <a href=\"home\">home</a>" +
                        "<br> <a href=\"logout\">logout</a>";
            case 403:
                logger.info("403异常跳转");
                return "You are not authorized to access this page." +
                        "<br> <a href=\"home\">home</a>" +
                        "<br> <a href=\"logout\">logout</a>";
            case 500:
                logger.info("500异常跳转");
                return "System exception." +
                        "<br> <a href=\"home\">home</a>" +
                        "<br> <a href=\"logout\">logout</a>";
            default:
                logger.info("默认异常跳转");
                return "Access page not found ." +
                        "<br> <a href=\"home\">home</a>" +
                        "<br> <a href=\"logout\">logout</a>";
        }
    }

    public static void main(String[] args) {
        SpringApplication.run(ErrorPageApp.class, args);
    }

}
